<template>
  <view class="add-device-container">
    <view class="title-bar">
      <text class="title">新增设备</text>
    </view>
    
    <scroll-view class="form-scroll" scroll-y>
      <form class="form-container" @submit="handleSubmit">
        <!-- 基础信息区域 -->
        <view class="form-section">
          <view class="section-header">基础信息</view>
          
          <view class="form-grid">
            <!-- 所属用户字段已隐藏 -->
            <!-- <view class="form-item">
              <text class="label">所属用户：</text>
              <input 
                type="text" 
                v-model="formData.userId" 
                placeholder="请输入所属用户" 
                class="input" 
              />
            </view> -->
            
            <view class="form-item">
              <text class="label">设备ID：</text>
              <view class="input-with-scan">
                <input 
                  type="text" 
                  v-model="formData.productSNo" 
                  placeholder="请输入设备ID或扫码获取" 
                  class="input scan-input" 
                />
                <button class="scan-button" @click="scanQRCode">
                  <text class="scan-icon">📷</text>
                </button>
              </view>
              <text class="error-text" v-if="errors.productSNo">{{ errors.productSNo }}</text>
            </view>
            
            <view class="form-item">
              <text class="label">设备标识：</text>
              <input 
                type="text" 
                v-model="formData.deviceId" 
                placeholder="请输入设备标识" 
                class="input" 
              />
              <text class="error-text" v-if="errors.deviceId">{{ errors.deviceId }}</text>
            </view>
            
            <!-- 其他表单项保持不变 -->
            <view class="form-item">
              <text class="label">通信模式：</text>
              <radio-group 
                class="radio-group"
                @change="e => formData.communicationMode = e.detail.value"
              >
                <label><radio value="无线公网" />无线公网</label>
                <label><radio value="无线专网" />无线专网</label>
              </radio-group>
              <text class="error-text" v-if="errors.communicationMode">{{ errors.communicationMode }}</text>
            </view>
            
            <view class="form-item">
              <text class="label">客户端ID：</text>
              <input 
                type="text" 
                v-model="formData.clientId" 
                placeholder="请输入客户端ID" 
                class="input" 
              />
            </view>
            
            <view class="form-item">
              <text class="label">用户名：</text>
              <input 
                type="text" 
                v-model="formData.username" 
                placeholder="请输入用户名" 
                class="input" 
              />
            </view>
            
            <view class="form-item">
              <text class="label">密码：</text>
              <input 
                type="password" 
                v-model="formData.password" 
                placeholder="请输入密码" 
                class="input" 
              />
            </view>
            
            <view class="form-item">
              <text class="label">安装地点：</text>
              <input 
                type="text" 
                v-model="formData.installationLocation" 
                placeholder="请输入安装地点" 
                class="input" 
              />
            </view>
            
            <view class="form-item">
              <text class="label">应用场景：</text>
              <radio-group 
                class="radio-group"
                @change="e => formData.applicationScenario = e.detail.value"
              >
                <label><radio value="配电变压器" />配电变压器</label>
                <label><radio value="配电分支箱" />配电分支箱</label>
                <label><radio value="个人/家庭" />个人/家庭</label>
                <label><radio value="充电桩" />充电桩</label>
                <label><radio value="其他应用" />其他应用</label>
              </radio-group>
              <text class="error-text" v-if="errors.applicationScenario">{{ errors.applicationScenario }}</text>
            </view>
          </view>
        </view>
        
        <!-- 其他表单区域保持不变 -->
        <!-- ... 其余代码保持不变 ... -->
        
        <!-- 线路信息区域 -->
        <view class="form-section">
          <view class="section-header">线路信息</view>
          
          <!-- 出线数量选择 -->
          <view class="form-item">
            <text class="label">出线数量：</text>
            <view class="outlet-selector">
              <view 
                v-for="num in 8" 
                :key="num"
                class="outlet-option"
                :class="{ active: selectedOutletCount === num }"
                @click="selectOutletCount(num)"
              >
                 {{ num }} 路
              </view>
            </view>
            <text class="error-text" v-if="errors.outletCount">{{ errors.outletCount }}</text>
          </view>
          
          <!-- 线路表头 -->
          <view class="lines-header" v-if="selectedOutletCount > 0">
            <view class="header-item name-header">线路名称</view>
            <view class="header-item capacity-header">额定容量（kVA）</view>
            <view class="header-item ratio-header">变比</view>
          </view>
          
          <!-- 动态线路表单项 -->
          <view v-for="i in selectedOutletCount" :key="i" class="line-row">
            <view class="line-number">线路 {{ i }} </view>
            <view class="line-inputs">
              <input 
                type="text" 
                v-model="formData[`line${i}Name`]" 
                placeholder="线路名称" 
                class="line-input name-input" 
              />
              <input 
                type="number" 
                v-model="formData[`line${i}RatedCapacity`]" 
                placeholder="容量值" 
                class="line-input capacity-input"
                @input="validateNumber(`line${i}RatedCapacity`)"
              />
              <input 
                type="number" 
                v-model="formData[`line${i}Ratio`]" 
                placeholder="变比数值" 
                class="line-input ratio-input"
                @input="validateNumber(`line${i}Ratio`)"
              />
            </view>
          </view>
        </view>
        
        <!-- 操作按钮区域 -->
        <view class="button-group">
          <button type="button" class="cancel-btn" @click="navigateBack">取消</button>
          <button formType="submit" class="save-btn">保存</button>
        </view>
      </form>
    </scroll-view>
  </view>
</template>

<script>
// 引入配置文件
import config from '../../config/index.js'
	
export default {
  data() {
    return {
      formData: {
        userId: 'default_user', // 设置默认用户ID
        productSNo: '',
        deviceId: '',
        communicationMode: '',
        clientId: '',
        username: '',
        password: '',
        installationLocation: '',
        applicationScenario: '',
        line10kvName: '',
        transformerName: '',
        transformerRatedCapacity: '',
        transformerRatio: '',
        mainInletName: '',
        mainInletRatedCapacity: '',
        mainInletRatio: '',
        // 8个线路的数据
        line1Name: '',
        line1RatedCapacity: '',
        line1Ratio: '',
        line2Name: '',
        line2RatedCapacity: '',
        line2Ratio: '',
        line3Name: '',
        line3RatedCapacity: '',
        line3Ratio: '',
        line4Name: '',
        line4RatedCapacity: '',
        line4Ratio: '',
        line5Name: '',
        line5RatedCapacity: '',
        line5Ratio: '',
        line6Name: '',
        line6RatedCapacity: '',
        line6Ratio: '',
        line7Name: '',
        line7RatedCapacity: '',
        line7Ratio: '',
        line8Name: '',
        line8RatedCapacity: '',
        line8Ratio: ''
      },
      errors: {},
      selectedOutletCount: 1 // 默认选择1路出线
    };
  },
  mounted() {
    // 添加WST回调函数支持
    window.javacalljswithargs = (arg) => {
      console.log('收到WST扫码结果:', arg);
      this.handleScanResult(arg);
    };

    // 监听扫码结果事件
    window.addEventListener('scanResult', (event) => {
      console.log('收到扫码结果事件:', event.detail);
      this.handleScanResult(event.detail.result);
    });

    // 监听WST就绪事件
    window.addEventListener('wstReady', (event) => {
      console.log('WST接口已就绪:', event.detail);
    });

    // 添加详细的环境检测日志
    this.logEnvironmentInfo();
  },
  beforeDestroy() {
    // 清理事件监听
    window.removeEventListener('scanResult', this.handleScanResult);
    window.removeEventListener('wstReady', this.handleWstReady);
  },
  methods: {
    // 添加环境信息日志
    logEnvironmentInfo() {
      console.log('=== 环境信息检测 ===');
      console.log('User Agent:', navigator.userAgent);
      console.log('Platform:', navigator.platform);
      console.log('Has WST:', !!window.wst);
      console.log('Has WST startFunction:', !!(window.wst && typeof window.wst.startFunction === 'function'));
      console.log('Has Android:', !!window.Android);
      console.log('Has Webkit:', !!(window.webkit && window.webkit.messageHandlers));
      console.log('Has plus:', typeof window.plus !== 'undefined');
      console.log('Has uni:', typeof uni !== 'undefined');
      console.log('Window keys:', Object.keys(window).filter(key => 
        ['wst', 'Android', 'webkit', 'plus', 'uni'].includes(key)));
      console.log('====================');
    },
    
    // 扫码功能 - 完全适配WST接口
    async scanQRCode() {
      console.log('=== 开始扫码流程 ===');
      
      // 阻止表单默认提交行为
      event.preventDefault();
      
      try {
        // 直接调用WebView扫码流程
        await this.scanQRCodeInWebView();
      } catch (error) {
        console.error('❌ 扫码功能异常:', error);
        this.showScanError();
      }
    },
    
    // WebView环境下的扫码 - 完全适配WST接口
    async scanQRCodeInWebView() {
      console.log('=== WebView扫码流程开始 ===');
      
      try {
        // 优先使用WST接口
        if (window.wst && typeof window.wst.startFunction === 'function') {
          console.log('✅ 发现WST接口，使用标准扫码');
          window.wst.startFunction('');
          return;
        }
        
        // 降级到原有接口
        console.log('⚠️ WST接口不可用，使用原有接口');
        if (window.Android && typeof window.Android.scanQRCode === 'function') {
          console.log('📱 使用Android原生接口');
          const result = await window.Android.scanQRCode();
          this.handleScanResult(result);
        } else if (window.webkit && window.webkit.messageHandlers.scanQRCode) {
          console.log('🍎 使用iOS原生接口');
          window.webkit.messageHandlers.scanQRCode.postMessage({
            callback: 'handleScanResult'
          });
        } else {
          console.error('❌ 所有扫码接口都不可用');
          this.showScanError();
        }
      } catch (error) {
        console.error('扫码过程中发生错误:', error);
        this.showScanError();
      }
    },

    // 显示扫码错误信息
    showScanError() {
      const errorMsg = '未发现WST接口或startFunction方法\n' +
                      'window.wst不存在\n' +
                      '未发现原生扫码接口\n' +
                      '当前可用的全局对象: ' + 
                      Object.keys(window).filter(key => 
                        !key.startsWith('_') && 
                        !key.startsWith('webkit') && 
                        key !== 'undefined' && 
                        key !== 'name' && 
                        key !== 'length' &&
                        typeof window[key] !== 'function'
                      ).join(', ');
      
      // 使用uni-app的提示
      if (typeof uni !== 'undefined' && uni.showModal) {
        uni.showModal({
          title: '扫码功能不可用',
          content: errorMsg,
          showCancel: false
        });
      } else {
        // 降级到alert
        alert(errorMsg);
      }
    },

    // 处理扫码结果
    handleScanResult(result) {
      console.log('收到扫码结果:', result);
      if (result && typeof result === 'string' && result.trim()) {
        this.formData.productSNo = result.trim();
        uni.showToast({
          title: '扫码成功',
          icon: 'success'
        });
        this.validateDeviceId(result.trim());
      } else {
        uni.showToast({ title: '扫码结果为空', icon: 'none' });
      }
    },
    
    // 验证设备ID是否存在
    async validateDeviceId(deviceId) {
      try {
        const token = uni.getStorageSync('token');
        const res = await uni.request({
          url: `${config.baseURL}/productDetail/checkDevice/${deviceId}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (res.data && res.data.code === 0) {
          uni.showToast({
            title: '设备ID验证通过',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '设备ID不存在，请检查',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('设备ID验证失败:', error);
        // 验证失败不影响继续操作
      }
    },
    
    // 选择出线数量
    selectOutletCount(count) {
      this.selectedOutletCount = count;
      // 根据选择的数量动态调整表单项
      for (let i = 1; i <= 8; i++) {
        this.$set(this.formData, `line${i}Name`, '');
        this.$set(this.formData, `line${i}RatedCapacity`, '');
        this.$set(this.formData, `line${i}Ratio`, '');
      }
    },
    
    // 数值验证
    validateNumber(field) {
      this.errors[field] = '';
      const value = this.formData[field];
      if (value && !/^-?\d+(\.\d+)?$/.test(value)) {
        this.errors[field] = '请输入有效的数值';
      }
    },
    
    // 表单验证
    validateForm() {
      let isValid = true;
      this.errors = {};

      if (!this.formData.productSNo) {
        this.errors.productSNo = '设备ID不能为空';
        isValid = false;
      }
      if (!this.formData.deviceId) {
        this.errors.deviceId = '设备标识不能为空';
        isValid = false;
      }
      if (!this.formData.communicationMode) {
        this.errors.communicationMode = '请选择通信模式';
        isValid = false;
      }
      if (!this.formData.applicationScenario) {
        this.errors.applicationScenario = '请选择应用场景';
        isValid = false;
      }
      if (this.selectedOutletCount === 0) {
        this.errors.outletCount = '请选择出线数量';
        isValid = false;
      }

      return isValid;
    },
    
    // 提交表单
    async handleSubmit() {
      if (!this.validateForm()) {
        uni.showToast({
          title: '请完善必填信息',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      try {
        // 构建提交数据，只包含用户选择的出线数量
        const submitData = {
          userId: this.formData.userId,
          productSNo: this.formData.productSNo,
          deviceId: this.formData.deviceId,
          communicationMode: this.formData.communicationMode,
          clientId: this.formData.clientId,
          username: this.formData.username,
          password: this.formData.password,
          installationLocation: this.formData.installationLocation,
          applicationScenario: this.formData.applicationScenario,
          lineNum: this.selectedOutletCount // 修复：使用正确的字段名lineNum
        };

        // 只添加用户选择的出线数量的数据
        for (let i = 1; i <= this.selectedOutletCount; i++) {
          submitData[`line${i}Name`] = this.formData[`line${i}Name`] || '';
          submitData[`line${i}RatedCapacity`] = this.formData[`line${i}RatedCapacity`] || '';
          submitData[`line${i}Ratio`] = this.formData[`line${i}Ratio`] || '';
        }

        console.log('提交的数据:', submitData);
        console.log('出线数量 (selectedOutletCount):', this.selectedOutletCount);
        console.log('出线数量 (lineNum):', submitData.lineNum);
        
        uni.showLoading({ title: '保存中...' });
        
        const res = await uni.request({
		  url:`${config.baseURL}/productDetail/save`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`,
            'Content-Type': 'application/json'
          },
          data: submitData
        });

        uni.hideLoading();
        
        if (res.data.code === 0) {
          // 处理返回的deviceId
          const deviceId = res.data.deviceId;
          if (deviceId && deviceId !== this.formData.productSNo) {
            console.log('获取到deviceId:', deviceId);
            uni.showModal({
              title: '保存成功',
              content: `设备标识: ${deviceId}`,
              showCancel: false,
              confirmText: '确定',
              success: () => {
                // 返回产品列表并刷新
                this.navigateBackAndRefresh();
              }
            });
          } else {
            uni.showToast({ title: '保存成功', icon: 'success' });
            setTimeout(() => {
              // 返回产品列表并刷新
              this.navigateBackAndRefresh();
            }, 1500);
          }
        } else {
          uni.showToast({ title: res.data.msg || '保存失败', icon: 'none' });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('保存失败:', error);
        uni.showToast({ title: '网络错误，请重试', icon: 'none' });
      }
    },
    
    // 返回上一页
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },
    
    // 返回并刷新产品列表
    navigateBackAndRefresh() {
      // 设置一个标记，表示需要刷新
      uni.setStorageSync('needRefreshProductList', true);
      uni.navigateBack({ delta: 1 });
    }
  }
};
</script>

<style scoped>
.add-device-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.title-bar {
  background-color: #2980ff;
  padding: 30rpx 20rpx;
  text-align: center;
}

.title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

.form-scroll {
  flex: 1;
  height: 1px;
  padding: 20rpx;
}

.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
}

/* 表单区块样式 */
.form-section {
  margin-bottom: 30rpx;
  padding: 10rpx;
}

.section-header {
  font-size: 30rpx;
  font-weight: bold;
  color: #2980ff;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
  border-left: 6rpx solid #2980ff;
}

/* 网格布局表单 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(45%, 1fr));
  gap: 20rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 15rpx;
  background-color: #fafafa;
  border-radius: 10rpx;
}

.label {
  font-size: 26rpx;
  color: #555;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.input {
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  padding: 18rpx 20rpx;
  font-size: 26rpx;
  color: #333;
  background-color: #fff;
}

.input:focus {
  border-color: #2980ff;
  outline: none;
}

/* 带扫码按钮的输入框容器 */
.input-with-scan {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  background-color: #fff;
  overflow: hidden;
}

.scan-input {
  flex: 1;
  border: none;
  padding: 18rpx 20rpx;
  font-size: 26rpx;
  color: #333;
  background-color: transparent;
  border-radius: 0;
}

.scan-input:focus {
  outline: none;
  box-shadow: none;
}

.scan-button {
  width: 80rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2980ff;
  border: none;
  border-left: 1px solid #e0e0e0;
  padding: 0;
  margin: 0;
}

.scan-icon {
  font-size: 32rpx;
  color: #fff;
}

.scan-button:active {
  background-color: #1e6de8;
}

.input-with-unit {
  display: flex;
  align-items: center;
}

.unit {
  border: 1px solid #e0e0e0;
  border-left: none;
  border-radius: 0 8rpx 8rpx 0;
  padding: 0 20rpx;
  font-size: 26rpx;
  color: #666;
  background-color: #f0f0f0;
  height: 70rpx;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx 30rpx;
  padding: 10rpx 0;
}

.radio-group label {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #333;
}

.radio-group radio {
  margin-right: 8rpx;
  transform: scale(1.1);
}

/* 出线数量选择器样式 */
.outlet-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 10rpx;
  padding: 15rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  border: 1px solid #e9ecef;
}

.outlet-option {
  padding: 12rpx 20rpx;
  font-size: 28rpx;
  color: #495057;
  background-color: #fff;
  border-radius: 8rpx;
  border: 2rpx solid #dee2e6;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 80rpx;
  text-align: center;
  font-weight: 500;
}

.outlet-option:active {
  transform: scale(0.95);
}

.outlet-option.active {
  background-color: #2980ff;
  color: #fff;
  border-color: #2980ff;
  box-shadow: 0 2rpx 8rpx rgba(41, 128, 255, 0.3);
}

/* 线路表格样式 */
.lines-header {
  display: flex;
  background-color: #f0f5ff;
  border-radius: 8rpx 8rpx 0 0;
  overflow: hidden;
  margin-bottom: 10rpx;
}

.header-item {
  font-size: 26rpx;
  font-weight: bold;
  color: #2980ff;
  padding: 15rpx;
  text-align: center;
}

.name-header {
  flex: 2;
}

.capacity-header, .ratio-header {
  flex: 1;
}

/* 线路行样式 */
.line-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  padding: 10rpx;
  background-color: #fafafa;
  border-radius: 8rpx;
}

.line-number {
  width: 80rpx;
  font-size: 26rpx;
  color: #666;
  text-align: center;
  font-weight: 500;
}

.line-inputs {
  flex: 1;
  display: flex;
  gap: 10rpx;
}

.line-input {
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  padding: 15rpx;
  font-size: 26rpx;
}

.name-input {
  flex: 2;
}

.capacity-input, .ratio-input {
  flex: 1;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
  padding: 10rpx;
}

.cancel-btn, .save-btn {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 10rpx;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #333;
}

.save-btn {
  background-color: #2980ff;
  color: #fff;
}

.save-btn:active {
  background-color: #1e6de8;
}

/* 错误提示 */
.error-text {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 8rpx;
  padding-left: 5rpx;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .scan-button {
    width: 70rpx;
    height: 65rpx;
  }
  
  .scan-icon {
    font-size: 28rpx;
  }
  
  .outlet-selector {
    gap: 8rpx;
    padding: 12rpx;
  }
  
  .outlet-option {
    padding: 10rpx 16rpx;
    font-size: 26rpx;
    min-width: 70rpx;
  }
}
</style>